<template>
  <div>
    <van-nav-bar :border="false" fixed title="兑换红包" left-arrow @click-left="GOback" placeholder />
    <van-form @submit="onSubmit">
      <van-field v-model="captcha_code" name="兑换码" placeholder="请输入兑换码" />
      <van-field v-model="exchange_code" name="验证码" placeholder="验证码" />
      <img @click="cation" :src="this.requ" alt="">
      <div style="margin: 16px;">
        <van-button round block type="info" native-type="submit" v-if="captcha_code&&exchange_code">兑换</van-button>
        <van-button round block type="info" native-type="submit" :disabled="true" v-else>兑换</van-button>
      </div>
    </van-form>
    <van-dialog v-model="show1" confirmButtonColor="#3199e8">
      <template #default>
        <div class="tip_icon">
          <span></span>
          <span></span>
        </div>
        <p class="tip_text">{{message}}</p>
      </template>
    </van-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //验证码base64地址
      requ: '',
      // 验证码
      captcha_code: '',
      // 兑换码
      exchange_code: '',
      show1: false,
      // 兑换失败
      message: ''
    }
  },
  methods: {
    GOback() {
      this.$router.go(-1)
    },
    //验证码
    async cation() {
      // this.$store.dispatch('cationinfo')
      const { data: res } = await this.reques.post('v1/captchas')
      this.requ = res.code
    },
    // 发起兑换红包请求
    async onSubmit() {
      const id = window.sessionStorage.getItem('user_id')
      const { data: res } = await this.reques.post(`v1/users/${id}/hongbao/exchange`, {
        captcha_code: this.captcha_code,
        exchange_code: this.exchange_code
      })
      if (res.message) {
        this.message = res.message
        this.show1 = true
      }
    }
  },
  mounted() {
    this.cation()
  }
}
</script>

<style lang="less" scoped>
.van-form {
  margin-top: 0.7rem;
}
img {
  top: 4.5rem;
  right: 1rem;
  position: absolute;
}
</style>